import hashlib

from flask import Blueprint, render_template, request, redirect, url_for, jsonify, g
from sqlalchemy import or_

from apps.article.models import Article
from apps.user.models import User
from ext import db

user_bp1 = Blueprint('user', __name__, url_prefix='/user')
required_login_list = ['/user/show', '/user/manager', '/user/update', '/user/search', '/user/delete']  # 需要登录后才能浏览的页面


# 留言显示
@user_bp1.route('/show')
def show():
        articles = Article.query.all()
        return render_template('user/index.html', articles=articles, user=g.user)


# 用户管理
@user_bp1.route('/manager')
def index():
    if g.user.grade == 1:
        users = User.query.filter(User.isdelete == False).all()  # 用于逻辑删除
        return render_template('user/center.html', users=users, user=g.user)
    else:
        return redirect(url_for('user.show'))


# 注册
@user_bp1.route('/register', methods= ['POST', 'GET'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        repassword = request.form.get('repassword')
        phone = request.form.get('phone')
        if password == repassword:
            user = User()
            user.username = username
            user.password = hashlib.sha256(password.encode('utf-8')).hexdigest()  # 加密
            user.phone = phone
            # 添加
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('user.show'))  # 重定向跳转
        else:
            return '密码不一致'
    return render_template('user/register.html')


# 登录
@user_bp1.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # 验证 select * from user where username='xxxx';
        new_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        user_list = User.query.filter_by(username=username)
        for user in user_list:
            if user.password == new_password:
                response = redirect(url_for('user.show'))  # 设置cookie
                response.set_cookie('uid', str(user.id), max_age=1800)  # 存活时间1800秒
                return response
        else:
            return render_template('user/login.html', msg='用户名或者密码有误！')

    return render_template('user/login.html')


# 验证电话格式
@user_bp1.route('/checkphone', methods=['GET', 'POST'])
def check_phone():
    phone = request.args.get('phone')
    user = User.query.filter(User.phone == phone).all()
    # code 400不可用 200可用
    if len(user) > 0:
        return jsonify(code=400, msg='此号码已被注册')
    else:
        return jsonify(code=200, msg='此号码可用')


# 用户搜索
@user_bp1.route('/search')
def search():
    keyword = request.args.get('search')
    # 查询
    user_list = User.query.filter(or_(User.username.contains(keyword), User.phone.contains(keyword))).all()
    return render_template('user/center.html', users=user_list)


# 用户删除
@user_bp1.route('/delete', endpoint='delete')
def user_delete():
    id = request.args.get('id')
    user = User.query.get(id)
    # 逻辑删除
    user.isdelete = True
    db.session.commit()
    return redirect(url_for('user.index'))


# 用户更新
@user_bp1.route('/update', methods=['POST', 'GET'], endpoint='update')
def update_user():
    if request.method == 'POST':
        username = request.form.get('username')
        phone = request.form.get('phone')
        id = request.form.get('id')
        user = User.query.get(id)
        user.phone = phone
        user.username = username
        db.session.commit()
        return redirect(url_for('user.index'))
    else:
        id = request.args.get('id')
        user = User.query.get(id)
        return render_template('user/update.html', user=user)


# 退出
@user_bp1.route('/logout')
def logout():
    response = redirect(url_for('user.show'))
    response.delete_cookie('uid')  # 删除cookie
    return response


# 未登录跳转
@user_bp1.before_app_request
def before_request():
    if request.path in required_login_list:
        uid = request.cookies.get('uid', None)  # 从请求中拿cookie
        if uid:
            user = User.query.get(uid)
            g.user = user
        else:
            return render_template('user/login.html')


